package com.mulong.common.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.github.pagehelper.PageInterceptor;

import tk.mybatis.spring.annotation.MapperScan;

/**
 * MallDataSourceConfig
 * 
 * @author mulong
 * @data 2021-03-30 21:33:24
 */
@ConditionalOnProperty("spring.datasource.druid.mall.url")
@Configuration
@MapperScan(basePackages = MallDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "mallSqlSessionFactory")
public class MallDataSourceConfig {
    public static final String PACKAGE = "com.mulong.common.dao.mall";
    public static final String MAPPER_LOCATION = "classpath*:mapper/mall/*.xml";

    @Bean(name = "mallDataSource", initMethod = "init", destroyMethod = "close")
    @ConfigurationProperties(prefix = "spring.datasource.druid.mall")
    public DruidDataSource mallDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "mallSqlSessionFactory")
    public SqlSessionFactory mallSqlSessionFactory(
                    @Qualifier("mallDataSource") DataSource mallDataSource)
                    throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(mallDataSource);
        sessionFactory.setConfiguration(MybatisConfig.configuration());
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                        .getResources(MallDataSourceConfig.MAPPER_LOCATION));
        // 分页查询配置
        PageInterceptor pageHelper = new PageInterceptor();
        Properties properties = new Properties();
        pageHelper.setProperties(properties);
        sessionFactory.setPlugins(pageHelper);
        return sessionFactory.getObject();
    }

    @Bean(name = "mallTransactionManager")
    public DataSourceTransactionManager mallTransactionManager(
                    @Qualifier("mallDataSource") DataSource mallDataSource) {
        return new DataSourceTransactionManager(mallDataSource);
    }

}
